package com.biqee.util;

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;

import javax.servlet.ServletContext;

import org.apache.log4j.Logger;
import org.apache.velocity.tools.view.ToolboxManager;
import org.apache.velocity.tools.view.XMLToolboxManager;
import org.springframework.util.ResourceUtils;

import com.opensymphony.webwork.WebWorkConstants;
import com.opensymphony.webwork.config.Configuration;

public class VelocityManagerEx  extends
		com.opensymphony.webwork.views.velocity.VelocityManager {
	
	private final static Logger log = Logger.getLogger(VelocityManagerEx.class);
	
	public VelocityManagerEx() {
		String toolboxLocation = "toolbox.xml";
		if (Configuration.isSet(WebWorkConstants.WEBWORK_VELOCITY_TOOLBOXLOCATION)) {
            toolboxLocation = Configuration.get(WebWorkConstants.WEBWORK_VELOCITY_TOOLBOXLOCATION).toString();
        }
		
		if (toolboxLocation != null) {
            XMLToolboxManager mgr = new XMLToolboxManager();
            
            try {
	            URL config = ResourceUtils.getURL(toolboxLocation);
	            if (config != null) {
	            	InputStream in = config.openStream();
	            	try {
		            	mgr.load(in);
		            	toolboxManager = mgr;
		            } finally {
		            	try {
		            		in.close();
						} catch (IOException e) {
							log.warn("failed to close file: " + toolboxLocation);
						}
		            }
	            }
            } catch (Exception ex) {
            	log.error("failed to load configuration file: " + toolboxLocation, ex);
            }
        }
	}
	
	/*
private ToolContext getToolContext() throws IllegalStateException, IOException {
  if (toolContext == null) {
    XmlFactoryConfiguration factoryConfiguration = new XmlFactoryConfiguration("Default Tools");
    factoryConfiguration.read(getServletContext().getResourceAsStream(getToolboxConfigLocation()));
    ToolboxFactory factory = factoryConfiguration.createFactory();
    factory.configure(factoryConfiguration);
    toolContext = new ToolContext();
    for (String scope : Scope.values()) {
      toolContext.addToolbox(factory.createToolbox(scope));
    }
  }
  return toolContext;
}
	 */
	
	/*
	 * (non-Javadoc)
	 * @see com.opensymphony.webwork.views.velocity.VelocityManager#initToolbox(javax.servlet.ServletContext)
	 */
	protected void initToolbox(ServletContext context) {
		
	}

	public ToolboxManager getToolboxManager() {
		return toolboxManager;
	}
	
}
